package at.im.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import at.im.json.JSONPacker;
import at.im.json.JSONParser;
import at.im.sql.SQLConnection;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/**
 * 
 * @author Sarah
 *
 */
public class Server
{
	 public static void main(String[] args) throws Exception 
	 {
	        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
	        server.createContext("/rest", new MyHandler());
	        server.setExecutor(null);
	        server.start();
	 }

	 static class MyHandler implements HttpHandler 
	 { 
		 public void handle(HttpExchange exchange) throws IOException 
		 {
	            String response = "Response";
	            String requestBody = readRequestBody(exchange.getRequestBody());
	            	            	            
	            JSONObject json = null;
				try 
				{
					json = new JSONObject(requestBody);

				} catch (JSONException e) 
				{
					e.printStackTrace();
				}
				
	            if(exchange.getRequestMethod().equals("POST"))		// POST
	            {
	            	new SQLConnection().connectToDatabase(0, JSONParser.parseJSON(json, 0), 4, "");
	            } else												// GET
	            {
	            	ArrayList<Object> list = new SQLConnection().connectToDatabase(0, null, 4, "12");
	            	for(int i=0; i<list.size(); i++)
	            	{
	            		response += JSONPacker.packObject(4, list.get(i)).toString();
	            	}
	            }
	           
	            exchange.sendResponseHeaders(200, response.length());
	            OutputStream os = exchange.getResponseBody();
	            os.write(response.getBytes());
	            os.close();
		 }
		 
		 private String readRequestBody(InputStream input)
		 {
			 BufferedReader bufferedReader;
			 try 
			 {
				 InputStreamReader isr 	= new InputStreamReader(input,"utf-8");
				 bufferedReader 		= new BufferedReader(isr);

	        	 int b;
	        	 StringBuilder buf = new StringBuilder(512);
	        	 while ((b = bufferedReader.read()) != -1) 
	        	     buf.append((char) b);

	        	 bufferedReader.close();
	        	 isr.close();
	        	 return buf.toString();
			} catch (Exception e) 
			{
				e.printStackTrace();
				return "failed";
			}
		 }
	 }
} 